package com.crane.oss.sys.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.BizException;
import com.crane.common.core.exception.SysException;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.sys.bean.request.dictdetail.AddDictDetailReq;
import com.crane.oss.sys.bean.request.dictdetail.UpdateDictDetailReq;
import com.crane.oss.sys.bean.request.dict.QueryDictDetailReq;
import com.crane.oss.sys.bean.resp.DictDetailResp;
import com.crane.oss.sys.dao.DictDao;
import com.crane.oss.sys.dao.DictDetailDao;
import com.crane.oss.sys.model.Dict;
import com.crane.oss.sys.model.DictDetail;
import com.crane.oss.sys.service.DictDetailService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhenxing.pi
 * @email ccsu123456@qq.com
 */
@Service
@Slf4j
public class DictDetailServiceImpl implements DictDetailService {

    @Resource
    protected DictDao dictDao;

    @Resource
    protected DictDetailDao dictDetailDao;

    @Override
    public DictDetailResp queryDictDetail(Long id) {
        log.info(" queryDictDetail id={}", id);
        DictDetail dictDetail = dictDetailDao.selectById(id);
        if (null == dictDetail) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "dictDetail");
        }
        Dict dict = dictDao.selectById(dictDetail.getDicGroupId());
        if (null == dict) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典分组");
        }
        DictDetailResp dictDetailResp = new DictDetailResp();
        BeanUtil.copyProperties(dictDetail, dictDetailResp);
        dictDetailResp.setDicGroupName(dict.getDictGroupName());
//        List<DictDetail> chirdList = dictDetailDao.selectList(Wrappers.lambdaQuery(DictDetail.class).eq(DictDetail::getPId, id));
//        if (CollectionUtils.isNotEmpty(chirdList)) {
//            List<DictDetailResp> list = BeanUtil.copyList(chirdList, DictDetailResp.class);
//            dictDetailResp.setChirdList(list);
//        }
        return dictDetailResp;
    }

	@Override
    public List<DictDetailResp> queryDictDetailList(Collection collection) {
        log.info(" queryDictDetailList collection={}", JSON.toJSONString(collection));
        List<DictDetail> list = dictDetailDao.selectBatchIds(collection);
        List<DictDetailResp> resultList = BeanUtil.copyList(list, DictDetailResp.class);
        return resultList;
    }

    @Override
    public IPage<DictDetailResp> queryList(QueryDictDetailReq queryRequest) {
        log.info(" queryList queryRequest={}", queryRequest);
        LambdaQueryWrapper<DictDetail> queryDictDetailWrapper = new LambdaQueryWrapper<>();
        Dict dict = null;
        if (null != queryRequest.getPId()) {
            queryDictDetailWrapper.eq(ObjectUtils.isNotNull(queryRequest.getPId()), DictDetail::getPId, queryRequest.getPId());
        } else {
            if (null == queryRequest.getDictGroupCode()) {
                throw new BizException("字典分组不能为空");
            }
            dict = dictDao.selectOne(Wrappers.lambdaQuery(Dict.class).eq(Dict::getDictGroupCode, queryRequest.getDictGroupCode()));
            if (null == dict) {
                throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典分组");
            }
            queryDictDetailWrapper.eq(DictDetail::getDicGroupId, dict.getId());
        }
        IPage<DictDetailResp> result = new Page<>();
        result.setCurrent(queryRequest.getPageNo());
        result.setPages(queryRequest.getPageSize());

        Page<DictDetail> page = new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize());
        IPage<DictDetail> iPage = dictDetailDao.selectPage(page, queryDictDetailWrapper);
        if (CollectionUtils.isEmpty(iPage.getRecords())) {
            result.setTotal(0);
            return result;
        }
        result.setTotal(iPage.getTotal());
        List<DictDetailResp> copyList = BeanUtil.copyList(iPage.getRecords(), DictDetailResp.class);

        List<DictDetailResp> resultList = new ArrayList<DictDetailResp>();
        for (DictDetailResp resp : copyList) {
        	DictDetailResp resultResp = new DictDetailResp();
        	BeanUtil.copyProperties(resp, resultResp);
        	if (null != resp.getPId()) {
            	DictDetail parentDictDetail = dictDetailDao.selectById(resp.getPId());
            	if (null != parentDictDetail) {
                	Dict parentDict = dictDao.selectById(parentDictDetail.getDicGroupId());
                	resultResp.setDicGroupName(parentDict.getDictGroupName());
                	resultResp.setPDictName(parentDictDetail.getDictName());
            	}
        	}

        	resultList.add(resultResp);
        }

//        String pDictName = "";
//        if (resultList.get(0).getPId() != null) {
//            DictDetail parentDictDetail = dictDetailDao.selectById(resultList.get(0).getPId());
//            if (parentDictDetail == null) {
//                throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "父字典");
//            }
//            pDictName = parentDictDetail.getDictName();
//            if (null == dict) {
//                dict = dictDao.selectById(resultList.get(0).getDicGroupId());
//            }
//        }
//        String finalPDictName = pDictName;
//        Dict finalDict = dict;
//        resultList.forEach(c -> {
//            c.setDicGroupName(finalDict.getDictGroupName());
//            c.setPDictName(finalPDictName);
//        });

        result.setRecords(resultList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(AddDictDetailReq addRequest) {
        log.info("--->save request={}", addRequest);
        if (null == addRequest.getDicGroupId()) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典分组");
        }
        Dict dict = dictDao.selectById(addRequest.getDicGroupId());
        if (null == dict) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典分组");
        }
        int level = 1;
        if (null != addRequest.getPId()) {
            DictDetail parentDictDetail = dictDetailDao.selectById(addRequest.getPId());
            if (parentDictDetail == null) {
                throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "父字典");
            }
            level = parentDictDetail.getLevel() + 1;
        }
        //验证 查询是否存在明细
        List<DictDetail> dickDetailList = dictDetailDao.selectList(Wrappers.lambdaQuery(DictDetail.class)
                .eq(DictDetail::getDicGroupId, addRequest.getDicGroupId()));
        if (CollectionUtils.isNotEmpty(dickDetailList)) {
            DictDetail dictDetail = dickDetailList.get(0);
//            addRequest.setPId(dictDetail.getPId());
            level = dictDetail.getLevel();
            dickDetailList.forEach(e -> {
            	if (null != addRequest.getPId()) {
                    if (e.getDicGroupId().equals(addRequest.getDicGroupId()) && e.getPId().equals(addRequest.getPId()) &&
                            (e.getDictName().equals(addRequest.getDictName()) && e.getDictValue().equals(addRequest.getDictValue()))) {
                        throw new BizException("字典已存在");
                    }
            	} else {
                    if (e.getDicGroupId().equals(addRequest.getDicGroupId()) &&
                            (e.getDictName().equals(addRequest.getDictName()) && e.getDictValue().equals(addRequest.getDictValue()))) {
                        throw new BizException("字典已存在");
                    }
            	}
            });
        }
        DictDetail dictDetail = new DictDetail();
        BeanUtil.copyProperties(addRequest, dictDetail);
        dictDetail.setLevel(level);
        dictDetail.setCreateTime(new Date());
        int i = 0;
        try {
            i = dictDetailDao.insert(dictDetail);
        } catch (Exception e) {
            log.info(" save exception={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(UpdateDictDetailReq updateRequest) {
        log.info(" update request={}", updateRequest);
        DictDetail dictDetail = dictDetailDao.selectById(updateRequest.getId());
        if (null == dictDetail) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典");
        }

        int count = dictDetailDao.selectCount(Wrappers.lambdaQuery(DictDetail.class)
                .eq(DictDetail::getDicGroupId, dictDetail.getDicGroupId())
                .eq(DictDetail::getDictName, updateRequest.getDictName())
                .eq(DictDetail::getDictValue, updateRequest.getDictValue())
                .eq(DictDetail::getLevel, dictDetail.getLevel())
                .ne(DictDetail::getId, updateRequest.getId()));
        if (count > 0) {
            throw new BizException("字典已存在");
        }
        DictDetail updateDictDetail = new DictDetail();
        BeanUtil.copyProperties(updateRequest, updateDictDetail);
        updateDictDetail.setUpdateTime(new Date());
        int i = 0;
        try {
            i = dictDetailDao.updateById(updateDictDetail);
        } catch (Exception e) {
            log.info(" update exception={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.info(" delete id={}", id);
        //不做递归遍历删除了
        return dictDetailDao.deleteById(id);
    }

}
